<template>
    <!-- 单根 -->
    <div>
        <el-row>
            <div style="width: 200px;">
                <el-input v-model="search" @blur="loadApp" clearable>
                    <template #prepend>查询</template>
                </el-input>
            </div>
            <div style="flex-grow: 1;"></div>
            <el-button @click="openAppDialogForAdd" type="primary" plain v-if="checkPermission('app:add')">添加应用
            </el-button>
        </el-row>
        <el-table :data="tableData" stripe v-loading="tableLoading" :highlight-current-row="true">
            <el-table-column type="expand">
                <template #default="data">
                    <el-form class="app-extra" label-width="auto">
                        <el-form-item label="访问URL"> {{ data.row.visitUrl }}</el-form-item>
                        <el-form-item label="git URL"> {{ data.row.gitUrl }}</el-form-item>
                        <el-form-item label="项目描述"> {{ data.row.description }}</el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column prop="id" label="应用id" width="80px"/>
            <el-table-column prop="name" label="应用名称" width="150px"/>
            <el-table-column prop="belongServerIp" label="所属服务器IP" width="150px"/>
            <el-table-column prop="projectFilePath" label="项目文件路径" width="200px">
                <template #default="data">
                    {{ data.row.projectFilePath }}
                    <el-icon v-if="data.row.projectFilePath" @click="copyText(data.row.projectFilePath)"
                             style="cursor: pointer;">
                        <CopyDocumentIcon/>
                    </el-icon>
                </template>
            </el-table-column>
            <el-table-column prop="option" label="操作">
                <template #default="data">
                    <el-button type="info" plain size="small" :disable="!appDialogVisible"
                               @click="openAppDialogForEdit(data.row)" v-if="checkPermission('app:edit')">
                        编辑
                    </el-button>
                    <el-button type="danger" plain size="small" :disable="!appDialogVisible"
                               @click="removeApp(data.row)"
                               v-if="checkPermission('app:remove')">
                        删除
                    </el-button>
                    <el-button v-if="data.row.visitUrl" type="primary" plain size="small" @click="enterApp(data.row)">
                        进入应用
                    </el-button>
                    <el-button v-if="data.row.gitUrl" type="primary" plain size="small" @click="enterGit(data.row)">
                        git
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 应用对话框 -->
        <el-dialog v-model="appDialogVisible" :title="appDialogTitle" width="600px" draggable>
            <template #default>
                <el-form v-if="appDialogForm" :model="appDialogForm" v-loading="appDialogFormLoading"
                         label-width="auto"
                         :rules="appDialogFormFormRules" ref="appDialogFormRef">
                    <el-form-item label="应用名称" prop="name">
                        <el-input v-model="appDialogForm.name">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="所属服务器IP">
                        <el-input v-model="appDialogForm.belongServerIp">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="访问URL">
                        <el-input v-model="appDialogForm.visitUrl">
                        </el-input>
                        <el-text size="small" tag="sub">需要填写http://或https://</el-text>
                    </el-form-item>
                    <el-form-item label="项目文件路径">
                        <el-input v-model="appDialogForm.projectFilePath">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="git URL">
                        <el-input v-model="appDialogForm.gitUrl">
                        </el-input>
                        <el-text size="small" tag="sub">需要填写http://或https://</el-text>
                    </el-form-item>
                    <el-form-item label="项目描述">
                        <el-input type="textarea" v-model="appDialogForm.description">
                        </el-input>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <el-button @click="appDialogVisible = false" :loading="appDialogFormSubmitLoading">关闭</el-button>
                <el-button @click="appDialogFormReset">重置</el-button>
                <el-button type="primary" @click="appDialogFormSubmit">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue'
import {ElMessage, FormRules, FormInstance, ElMessageBox} from 'element-plus';
import {CopyDocument as CopyDocumentIcon} from '@element-plus/icons-vue'
import * as clipboard from 'clipboard'
import {myAxios} from '../assets/ts/my-axios'
import {checkPermission} from '../assets/ts/permission-util'

const tableData = ref<Array<AppInfo>>([])

// 表格加载遮罩
const tableLoading = ref(false)

// 生命周期 - 挂载
onMounted(() => {
    loadApp()
    console.log(import.meta.env.VITE_PROJECT_PREFIX)
})


// 进入应用
function enterApp(appInfo: AppInfo) {
    window.open(appInfo.visitUrl)
}

// 进入git
function enterGit(appInfo: AppInfo) {
    window.open(appInfo.gitUrl)
}

// 复制项目路径
function copyText(text: string) {
    clipboard.copy(text)
    ElMessage.success('已复制到剪切板')
}

// ====================================== 定义 ===========================================

// 项目应用信息抽象
export interface AppInfo {
    id: number,
    name: string,
    belongServerIp?: string,
    // 访问URL
    visitUrl?: string,
    // 项目文件路径
    projectFilePath?: string,
    // git url
    gitUrl?: string,
    // 项目描述
    description?: string,
}

// 项目应用详情
export interface AppDetail {
    id: number,
    name: string,
    belongServerIp?: string,
    // 访问URL
    visitUrl?: string,
    // 项目文件路径
    projectFilePath?: string,
    // git url
    gitUrl?: string,
    // 项目描述
    description?: string,
}

// ====================================== 应用表格 ===========================================

const search = ref('')

// 加载应用列表
function loadApp() {
    tableLoading.value = true
    let params = {search: search.value}
    myAxios.get('/app/list', {params: params})
        .then((response: any) => {
            if (response.data.code == 0) {
                tableData.value = response.data.data
            } else {
                ElMessage.error(response.data.message)
            }
        }).finally(() => {
        tableLoading.value = false
    })
}

// ====================================== 应用对话框 ===========================================

enum AppDialogType { add, edit }

const appDialogVisible = ref(false)
const appDialogTitle = ref('')
const appDialogType = ref(AppDialogType.add)
const appDialogForm = ref<AppDetail>()
const appDialogFormRef = ref<FormInstance>()
const appDialogFormLoading = ref(false)
const appDialogFormSubmitLoading = ref(false)
let appDialogFormSource: AppDetail


// 打开对话框，编辑应用
function openAppDialogForEdit(appInfo: AppInfo) {
    // 类型为编辑
    appDialogType.value = AppDialogType.edit
    appDialogTitle.value = '编辑应用'
    // 表单初始化
    appDialogFormSource = {...appInfo}
    appDialogFormReset()
    // 展示面板
    appDialogVisible.value = true
}

// 打开对话框，添加应用
function openAppDialogForAdd() {
    // 类型为添加
    appDialogType.value = AppDialogType.add
    appDialogTitle.value = '添加应用'
    // 表单初始化
    appDialogFormSource = {id: 0, name: ''}
    appDialogFormReset()
    // 展示面板
    appDialogVisible.value = true
}

// 表单重置
function appDialogFormReset() {
    appDialogForm.value = {...appDialogFormSource}
    appDialogFormRef.value?.clearValidate()
}

// 表单验证规则
const appDialogFormFormRules = ref<FormRules>({
    id: [
        {required: true, message: "请输入应用名id", trigger: "blur"},
        {type: 'number', message: "必须为数字", trigger: "blur"},
    ],
    name: [
        {required: true, message: "请输入应用名称", trigger: "blur"},
        {min: 3, max: 16, message: "长度限制为3-16字符", trigger: "blur"},
    ],
})

// 表单提交
function appDialogFormSubmit() {
    // TODO 开启验证
    appDialogFormRef.value?.validate((valid, _fields) => {
        if (valid) {
            let apiUrl =
                appDialogType.value == AppDialogType.add ? '/app/add'
                    : appDialogType.value == AppDialogType.edit ? '/app/edit'
                        : ''
            appDialogFormSubmitLoading.value = true
            myAxios.post(apiUrl, appDialogForm.value)
                .then((response: any) => {
                    if (response.data.code == -1) {
                        ElMessage.error(response.data.message)
                    } else {
                        ElMessage.success("保存成功")
                        loadApp()
                        appDialogVisible.value = false
                    }
                }).finally(() => {
                appDialogFormSubmitLoading.value = false
            })
        }
    })
}

// 删除应用
function removeApp(appInfo: AppInfo) {
    ElMessageBox.confirm(
        '是否确认删除应用:' + appInfo.name,
        '删除应用',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 删除权限
        myAxios.post('/app/remove', {appId: appInfo.id}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response) => {
                    if (response.data.code == 0) {
                        ElMessage.success("删除成功")
                        loadApp()
                    } else {
                        ElMessage.error(response.data.message)
                    }
                }
            )
    }).catch((e: any) => {
        console.log("取消 e:" + e)
    })
}

</script>

<style scoped>
.el-table {
    width: 100%;
}

.el-form.app-extra {
    border: 2px solid var(--el-menu-border-color);

    .el-form-item {
        margin-bottom: 0px;
    }

}
</style>